<template>
  <div class="component-upload-image">
    <el-upload
      multiple
      :action="uploadImgUrl"
      list-type="picture-card"
      :on-success="handleUploadSuccess"
      :before-upload="handleBeforeUpload"
      :limit="limit"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      ref="imageUpload"
      :on-remove="handleDelete"
      :show-file-list="true"
      :headers="headers"
      :file-list="fileList"
      :on-preview="handlePictureCardPreview"
      :class="{hide: fileList.length >= limit}"
    >
      <i class="el-icon-plus"></i>
    </el-upload>

    <div class="el-upload__tip" slot="tip" v-if="showTip">
      请上传
      <template v-if="fileSize">大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b></template>
      <template v-if="fileType">格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b></template>
      的文件
    </div>

    <el-dialog :visible.sync="dialogVisible" title="预览" width="800" append-to-body>
      <img :src="dialogImageUrl" style="display: block; max-width: 100%; margin: 0 auto"/>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { isExternal } from "@/utils/validate";
import { deleteFromOss } from "@/api/kiku/common";

export default {
  name: "OssImageUpload",
  props: {
    value: {
      type: [String, Object, Array],
      default: ""
    },
    limit: {
      type: Number,
      default: 5,
      validator: value => value > 0
    },
    fileSize: {
      type: Number,
      default: 5,
      validator: value => value > 0
    },
    fileType: {
      type: Array,
      default: () => ["png", "jpg", "jpeg"],
      validator: value => value.every(type => typeof type === "string")
    },
    isShowTip: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      number: 0,
      uploadList: [],
      dialogImageUrl: "",
      dialogVisible: false,
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadImgUrl: `https://manage.kiku001.top/prod-api/common/uploadToOss`,
      headers: {
        Authorization: `Bearer ${getToken()}`
      },
      fileList: []
    };
  },
  computed: {
    showTip() {
      return this.isShowTip && (this.fileType.length > 0 || this.fileSize > 0);
    }
  },
  watch: {
    value: {
      handler(val) {
        this.updateFileList(val);
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    // 更新文件列表
    updateFileList(val) {
      if (!val) {
        this.fileList = [];
        return;
      }

      const list = Array.isArray(val) ? val : val.toString().split(',');
      this.fileList = list.map(item => {
        if (typeof item === "string") {
          const url = this.normalizeUrl(item);
          return { name: url, url };
        }
        return item;
      });
    },

    // 规范化URL
    normalizeUrl(url) {
      if (!url) return url;
      if (isExternal(url) || url.startsWith(this.baseUrl)) {
        return url;
      }
      return `${this.baseUrl}${url}`;
    },

    // 上传前校验
    handleBeforeUpload(file) {
      // 校验文件类型
      const extension = file.name.split('.').pop().toLowerCase();
      const typeValid = this.fileType.includes(extension);
      if (!typeValid) {
        this.$modal.msgError(`请上传 ${this.fileType.join('/')} 格式的文件!`);
        return false;
      }

      // 校验文件名
      if (file.name.includes(',')) {
        this.$modal.msgError('文件名不能包含英文逗号!');
        return false;
      }

      // 校验文件大小
      const sizeValid = file.size / 1024 / 1024 < this.fileSize;
      if (!sizeValid) {
        this.$modal.msgError(`文件大小不能超过 ${this.fileSize}MB!`);
        return false;
      }

      this.$modal.loading("正在上传图片，请稍候...");
      this.number++;
      return true;
    },

    // 处理上传成功
    handleUploadSuccess(res, file) {
      if (res.code === 200) {
        this.uploadList.push({ name: res.fileName, url: res.url });
        this.uploadedSuccessfully();
      } else {
        this.handleUploadError(res.msg);
        this.$refs.imageUpload.handleRemove(file);
      }
    },

    // 处理上传失败
    handleUploadError(err) {
      this.number--;
      this.$modal.closeLoading();
      const errorMsg = typeof err === 'string' ? err : '上传图片失败，请重试';
      this.$modal.msgError(errorMsg);
    },

    // 文件数量超出限制
    handleExceed() {
      this.$modal.msgError(`最多只能上传 ${this.limit} 个文件!`);
    },

    // 删除文件
    async handleDelete(file) {
      try {
        const ossUrl = new URL(file.url);
        const fileName = ossUrl.pathname.substring(1);
        await deleteFromOss(fileName);
        this.$modal.msgSuccess("删除成功");

        // 更新文件列表
        this.fileList = this.fileList.filter(item => item.url !== file.url);
        this.$emit("input", this.listToString(this.fileList));
      } catch (error) {
        const errorMsg = error.response?.data?.msg || error.message || "删除失败";
        this.$modal.msgError(`删除失败: ${errorMsg}`);
      }
    },

    // 上传完成处理
    uploadedSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.fileList = [...this.fileList, ...this.uploadList];
        this.uploadList = [];
        this.number = 0;
        this.$emit("input", this.listToString(this.fileList));
        this.$modal.closeLoading();
      }
    },

    // 预览图片
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    // 文件列表转字符串
    listToString(list, separator = ",") {
      return list
        .map(item => item.url.replace(this.baseUrl, ""))
        .filter(url => url)
        .join(separator);
    }
  }
};
</script>

<style scoped lang="scss">
::v-deep.hide .el-upload--picture-card {
  display: none;
}

::v-deep .el-list-enter-active,
::v-deep .el-list-leave-active {
  transition: all 0s;
}

::v-deep .el-list-enter,
::v-deep .el-list-leave-active {
  opacity: 0;
  transform: translateY(0);
}
</style>
